/**
 * @Date: Feb 19, 2010 6:49:00 PM
 */
package com.philip.journal.login.service;

import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;

import com.philip.journal.core.Constant;
import com.philip.journal.core.bean.User;
import com.philip.journal.core.service.BaseService;
import com.philip.journal.login.service.exception.IncorrectPasswordException;
import com.philip.journal.login.service.exception.UserNotFoundException;
import com.philip.journal.login.service.util.PasswordUtil;

/**
 * @author cry30
 */
public class LoginServiceImpl extends BaseService implements LoginService {

    /** Instance logger. */
    private final Logger logger = Logger.getLogger(getClass()); // NOPMD by r39

    @Override
    public User authenticateUser(final Map<String, Object> session, final String username, final String pPassword)
    {
        final User user = getDaoFacade().getUserDAO().readByUsername(username);
        if (user == null) {
            throw new UserNotFoundException(username);
        } else {
            final String password = pPassword == null ? "" : pPassword;
            if (PasswordUtil.getInstance().checkPassword(user, password) || password.equals(user.getPassword())) {
                session.put(Constant.CURRENT_USER, user);
                return user;
            } else {
                logger.debug(PasswordUtil.getInstance().encrypt(user, password));
                logger.debug(user.getPassword());
                throw new IncorrectPasswordException();
            }
        }
    }

    @Override
    public void changePassword(final Map<String, Object> session, final String oldPassword, final String pNewPassword)
    {
        final String newPassword = pNewPassword == null ? "" : pNewPassword;
        User user = (User) session.get(Constant.CURRENT_USER);
        user = getDaoFacade().getUserDAO().readByUsername(user.getUsername());
        if (PasswordUtil.getInstance().checkPassword(user, oldPassword) || oldPassword.equals(user.getPassword())) {
            final Date now = new Date();
            user.setUpdateDate(now);
            user.setUpdateTime(now);
            user.setUpdater(user);
            user.setPassword(PasswordUtil.getInstance().encrypt(user, newPassword));
            // user.setChecksum(PasswordUtil.encrypt(user, user.getPassword() + user.getClass()));
            getDaoFacade().getUserDAO().save(user);
        } else {
            throw new IncorrectPasswordException();
        }
    }

    @Override
    public User getCurrentUser(final Map<String, Object> session)
    {
        return (User) session.get(Constant.CURRENT_USER);
    }
}